package com.ruoyi.repayment.controller;

import com.aliyun.oss.OSS;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import com.ruoyi.repayment.pojo.User;
import com.ruoyi.repayment.service.LoanService;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Date;

/**
 * @description: TODO
 * @author admin
 * @date 2022/10/1613:00
 * @version 1.0
 */
@RequestMapping("/file/upload")
@RestController
@CrossOrigin
public class NativeUploadController {

    @Value("${oss.bucket}")
    private String bucketName;

    @Value("${oss.hostName}")
    private String hostName;

    @Autowired
    private OSS ossClient;

    @Autowired
    LoanService loanService;


    /*
     * 文件下载api
     * @param: fileName
     * @param: response
     * @return: com.alibaba.fastjson.JSONObject
     * @create: 2020/10/31 17:35
     * @author: csp1999
     */



    @PostMapping("/native/{userId}")
    public String nativeUpload(@PathVariable("userId")Long userId) throws IOException, DocumentException {

        int num = (int)(Math.random()*100);
        Document document = new Document();
        String pdfName = num+"合同.pdf";
        //建立一个书写器
        PdfWriter writer = PdfWriter.getInstance(document,new FileOutputStream("D:\\youxi\\"+pdfName));
        //打开文档
        document.open();
        BaseFont bf =  BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        Font font = new Font(bf,20,Font.BOLD);	//字体颜色有三个参数，输出中文格式，字体大小，字体特点比如加粗
        Paragraph paragraph = new Paragraph("贷款合同",font);	//段落
        paragraph.setFirstLineIndent(14);		//缩进
        paragraph.setAlignment(1);		//1为居中对齐、2为右对齐、3为左对齐，默认为左对齐


        Chunk temp = new Chunk("产品小额贷款\n",font);
        Chunk temp2 = new Chunk("贷款时间"+new Date()+"\n",font);
        Chunk temp3 = new Chunk("贷款金额:8000\n",font);
        /*   temp.setBackground(BaseColor.BLUE);	*/	//背景颜色
        temp.setTextRise(10);		//文本框大小

        //添加内容
        document.add(paragraph);
        document.add(temp);
        document.add(temp2);
        document.add(temp3);
        Image image = Image.getInstance("D:\\实训一\\index.png");
        image.scaleToFit(100f, 100f);			//图片大小	宽度，高度
        image .setAlignment(Image.RIGHT);		//图片居中   Image.RIGHT、Image.MIDDLE、Image.LEFT分别指右对齐、居中、左对齐
        document.add(image);

        Image image2 = Image.getInstance("https://zwhy1.oss-cn-beijing.aliyuncs.com/"+userId+".jpg");
        image.scaleToFit(100f, 100f);			//图片大小	宽度，高度
        image .setAlignment(Image.LEFT);		//图片居中   Image.RIGHT、Image.MIDDLE、Image.LEFT分别指右对齐、居中、左对齐
        document.add(image2);


        //关闭文档
        document.close();
        //关闭书写器
        writer.close();
        User user = loanService.loginUser(userId);
        InputStream inputStream = new FileInputStream("D:\\实训一\\"+pdfName);
        ossClient.putObject(bucketName,user.getPhone()+".pdf",inputStream);
        // 关闭OSSClient。
        ossClient.shutdown();
        System.out.println("上传成功");
        System.out.println(hostName+""+pdfName);
        return  hostName+pdfName;


    }


    /**
     * 转换全部的pdf
     * @param fileAddress 文件地址
     * @param filename PDF文件名
     * @param type 图片类型
     */
    public static void pdf2png(String fileAddress,String filename,String type) {
        // 将pdf装图片 并且自定义图片得格式大小
        File file = new File(fileAddress+"\\"+filename+".pdf");
        try {
            PDDocument doc = PDDocument.load(file);
            PDFRenderer renderer = new PDFRenderer(doc);
            int pageCount = doc.getNumberOfPages();
            for (int i = 0; i < pageCount; i++) {
                BufferedImage image = renderer.renderImageWithDPI(i, 144); // Windows native DPI
                // BufferedImage srcImage = resize(image, 240, 240);//产生缩略图
                ImageIO.write(image, type, new File(fileAddress+"\\"+filename+"_"+(i+1)+"."+type));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     *自由确定起始页和终止页
     * @param fileAddress 文件地址
     * @param filename pdf文件名
     * @param indexOfStart 开始页  开始转换的页码，从0开始
     * @param indexOfEnd 结束页  停止转换的页码，-1为全部
     * @param type 图片类型
     */
    public static void pdf2png(String fileAddress,String filename,int indexOfStart,int indexOfEnd,String type) {
        // 将pdf装图片 并且自定义图片得格式大小
        File file = new File(fileAddress+"\\"+filename+".pdf");
        try {
            PDDocument doc = PDDocument.load(file);
            PDFRenderer renderer = new PDFRenderer(doc);
            int pageCount = doc.getNumberOfPages();
            for (int i = indexOfStart; i < indexOfEnd; i++) {
                BufferedImage image = renderer.renderImageWithDPI(i, 144); // Windows native DPI
                // BufferedImage srcImage = resize(image, 240, 240);//产生缩略图
                ImageIO.write(image, type, new File(fileAddress+"\\"+filename+"_"+(i+1)+"."+type));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //完成oss的上传以及合同查看
}
